﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using System.ComponentModel;
using System.Windows;

namespace Kokomo.Controls
{
	public class PropertyViewItem : HeaderedContentControl
	{
		static PropertyViewItem()
		{
			DefaultStyleKeyProperty.OverrideMetadata(typeof(PropertyViewItem), new FrameworkPropertyMetadata(typeof(PropertyViewItem)));
		}

		public object Object { get; private set; }
		public PropertyDescriptor Property { get; private set; }
		public TypeConverter Converter { get; private set; }

		public PropertyViewItem(
			object obj,
			PropertyDescriptor property
			)
		{
			this.Object = obj;
			this.Property = property;
			this.Converter = property.Converter;

			this.RefreshContent();
		}

		protected virtual void RefreshContent()
		{
			if (
				(this.Object == null)
				|| (this.Property == null)
				)
			{
				this.Header = null;
				this.Content = null;
			}

			this.Header = this.Property.DisplayName;

			object propertyValue = this.Property.GetValue(this.Object);

			string text;
			if (
				(this.Converter != null)
				&& (this.Converter.CanConvertTo(typeof(string)))
				)
			{
				text = (string)this.Converter.ConvertTo(propertyValue, typeof(string));
			}
			else if (propertyValue == null)
			{
				text = "null";
			}
			else
			{
				text = propertyValue.ToString();
			}

			this.Content = text;
		}

		public string Category
		{
			get { return this.Property.Category; }
		}
	}
}
